package com.useeinfo.oa.open.admin.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.AliJsonObjectCover;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.PositionBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Position;
import com.useeinfo.oa.modules.base.entity.SystemUserOrganization;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.task.biz.TaskAuditOrderBiz;
import com.useeinfo.oa.modules.task.biz.TaskOrderBiz;
import com.useeinfo.oa.modules.task.entity.TaskOrder;
import com.useeinfo.oa.modules.task.enums.TaskOrderStatusEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @auther: bin.liu
 * @Date: 2019/7/1 14:34
 * @Description: 任务工单审批管理
 */
@Controller
@RequestMapping("/web/admin/taskOrderAudit")
public class TaskOrderAuditAction {

    @Autowired
    private TaskOrderBiz taskOrderBiz;

    @Autowired
    private SystemUserBiz systemUserBiz;

    @Autowired
    private OrganizationBiz organizationBiz;

    @Autowired
    private PositionBiz positionBiz;

    @Autowired
    private TaskAuditOrderBiz taskAuditOrderBiz;


    /**
     * 打开列表页面
     */
    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/taskOrderAudit/list");
        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "taskContent", required = false) String taskContent,
                               @RequestParam(value = "reportUser", required = false) String reportUser,
                               @RequestParam(value = "startTime", required = false) String startTime,
                               @RequestParam(value = "endTime", required = false) String endTime,
                               HttpServletRequest request){
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("serial", searchCode);
        queryParam.getSqlMap().put("taskContent", taskContent);
        queryParam.getSqlMap().put("createUser", reportUser);
        queryParam.getSqlMap().put("createDate1",startTime);
        queryParam.getSqlMap().put("createDate2",endTime);

        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(request);
        sessionUser = systemUserBiz.findModel(sessionUser.getId());
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
            SystemUserOrganization systemUserOrganization = sessionUser.getOrganization(enterprise, sessionUser.getSystemUserOrganizationSet());
            Position position = sessionUser.getPosition(enterprise, sessionUser.getPositionSet());
            if(systemUserOrganization != null){
                queryParam.getSqlMap().put("auditOrganizationId", StringConverters.null2String(systemUserOrganization.getOrganization().getId()));
            }
            queryParam.getSqlMap().put("auditUserId",StringConverters.null2String(sessionUser.getId()));
            if(position != null){
                queryParam.getSqlMap().put("auditPositionId",StringConverters.null2String(position.getId()));
            }
        }
        queryParam.getSqlMap().put("orderStatus","IN_AUDITING");

        return taskOrderBiz.findJSONList(queryParam);
    }



    /**
     * 审核不通过页面
     *
     * @param id
     * @param
     * @return
     */
    @RequestMapping("/auditOrderEdit")
    public ModelAndView auditOrderEdit(String id) {

        ModelAndView modelAndView = new ModelAndView();
        TaskOrder taskOrder = taskOrderBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("taskOrder", taskOrder);
        modelAndView.setViewName("pages/admin/taskOrderAudit/unPassOrder");
        return modelAndView;
    }

    /**
     * 终极审核评分页面
     *
     * @param id
     * @return
     */
    @RequestMapping("/judgeOrder")
    public ModelAndView judgeOrder(String id) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("taskOrderId", id);
        TaskOrder taskOrder = taskOrderBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("taskOrder", taskOrder);
        modelAndView.setViewName("pages/admin/taskOrderAudit/judgeTaskOrder");
        return modelAndView;
    }

    @RequestMapping("/audit")
    @ResponseBody
    public ResultDto audit(@RequestParam(value = "id", required = false) String id,
                           @RequestParam(value = "type",required = false) Boolean type, HttpServletRequest request,
                           String score, String remark, String reason){
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        TaskOrder taskOrder = taskOrderBiz.findModel(StringConverters.null2Long(id));
        JSONArray jsonArray = JSONArray.parseArray(taskOrder.getFlow());
        if (type) {
            // 审核通过
            //任务单中的审批流快照
            int auditLevel = taskOrder.getAuditLevel();
            if (jsonArray.size() > 0 && auditLevel + 1 < jsonArray.size()) {
                taskOrder.setAuditLevel(auditLevel + 1);
                taskOrder.setAuditUser(null);
                taskOrder.setAuditOrganization(null);
                taskOrder.setAuditPosition(null);
                JSONObject j = jsonArray.getJSONObject(auditLevel + 1);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                taskOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                if ("POSITION".equals(nodeTypeEnum)) {
                    taskOrder.setAuditPosition(positionBiz.findModel(relationId));
                } else if ("USER".equals(nodeTypeEnum)) {
                    taskOrder.setAuditUser(systemUserBiz.findModel(relationId));
                } else {
                    taskOrder.setAuditUser(taskOrder.getCreateUser());
                }
                taskAuditOrderBiz.saveOrUpdate(taskOrder, systemUser, true, remark,null, auditLevel);
            } else if (jsonArray.size() > 0 && auditLevel + 1 == jsonArray.size()) {
                if(StringUtils.isNotBlank(score)){
                    taskOrder.setLastScore(StringConverters.null2Int(score));
                }
                if(StringUtils.isNotBlank(remark)){
                    taskOrder.setLastRemark(remark);
                }
                // 审批人显示终审人员信息
                taskOrder.setAuditUser(systemUser);
                taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.COMPLETED);
                taskAuditOrderBiz.saveOrUpdate(taskOrder, systemUser, true, remark,null, auditLevel);
            }
        } else{
            if (StringUtils.isBlank(reason)){
                return ResultUtil.error("请输入驳回理由");
            }
            // 审核驳回
            int auditLevel = taskOrder.getAuditLevel();
            taskOrder.setTaskOrderStatus(TaskOrderStatusEnum.REJECTED);
            taskAuditOrderBiz.saveOrUpdate(taskOrder, systemUser, false,null, reason, auditLevel);
        }
        return ResultUtil.success();
    }
}
